<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>微信 JSSDK Node Demo</title>
  <style>
    body { font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif; padding: 20px; }
    .card { border: 1px solid #e5e7eb; border-radius: 8px; padding: 16px; margin-bottom: 12px; }
    code { background: #f3f4f6; padding: 2px 4px; border-radius: 4px; }
    .ok { color: #16a34a; }
    .warn { color: #eab308; }
    .err { color: #dc2626; }
    button { padding: 8px 12px; margin-right: 8px; }
  </style>
  <!-- 官方 JSSDK 文件，需在微信内置浏览器环境中使用 -->
  <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
</head>
<body>
  <h1>微信 JSSDK Node Demo</h1>

  <div class="card">
    <div id="env"></div>
    <div id="status" class="warn">初始化中…</div>
    <div id="error" class="err"></div>
  </div>

  <div class="card">
    <h2>步骤</h2>
    <ol>
      <li>将 <code>.env.example</code> 复制为 <code>.env</code>，填写测试号 <code>WECHAT_APP_ID</code> 与 <code>WECHAT_APP_SECRET</code>。</li>
      <li>将本页网址（不含 <code>#</code>）配置到测试号的「JS接口安全域名」。开发时可使用内网穿透（如 ngrok）。</li>
      <li>在微信内打开此页面，点击右上角分享菜单查看效果。</li>
    </ol>
  </div>

  <div class="card">
    <h2>JSSDK 调试</h2>
    <button id="btnCheck">checkJsApi</button>
    <button id="btnResetShare">设置分享信息</button>
    <button id="btnScanQRCode">扫描二维码</button>
    <pre id="log"></pre>
  </div>

  <script>
    const logEl = document.getElementById('log');
    const statusEl = document.getElementById('status');
    const errorEl = document.getElementById('error');
    const envEl = document.getElementById('env');

    const isWx = /MicroMessenger/i.test(navigator.userAgent);
    envEl.innerHTML = isWx ? '<span class="ok">检测到微信内置浏览器环境</span>' : '<span class="warn">未检测到微信浏览器，请在微信内打开本页</span>';

    function appendLog(msg) {
      logEl.textContent += `${msg}\n`;
    }

    async function fetchSignature() {
      const url = location.href.split('#')[0];
      const resp = await fetch(`/api/wechat-signature?url=${encodeURIComponent(url)}`);
      const json = await resp.json();
      if (!json.success) throw new Error(json.error || '签名接口返回失败');
      return json.data;
    }

    function setupShare() {
      const shareTitle = '微信 JSSDK Node 示例';
      const shareDesc = '使用 Node.js 后端生成签名，前端集成 JSSDK 调试';
      const shareLink = location.href.split('#')[0];
      const shareImg = `${location.origin}/favicon.ico`;

      // 分享给朋友
      if (wx.updateAppMessageShareData) {
        wx.updateAppMessageShareData({
          title: shareTitle,
          desc: shareDesc,
          link: shareLink,
          imgUrl: shareImg
        }, function(res){ appendLog('updateAppMessageShareData: ' + JSON.stringify(res)); });
      }
      // 分享到朋友圈
      if (wx.updateTimelineShareData) {
        wx.updateTimelineShareData({
          title: shareTitle,
          link: shareLink,
          imgUrl: shareImg
        }, function(res){ appendLog('updateTimelineShareData: ' + JSON.stringify(res)); });
      }
    }

    async function init() {
      try {
        statusEl.textContent = '获取签名…';
        const sig = await fetchSignature();
        appendLog('signature: ' + JSON.stringify(sig, null, 2));
        statusEl.textContent = '调用 wx.config…';
        wx.config({
          debug: true, // 若不需要调试可改为 false
          appId: sig.appId,
          timestamp: sig.timestamp,
          nonceStr: sig.nonceStr,
          signature: sig.signature,
          jsApiList: ['checkJsApi', 'updateAppMessageShareData', 'updateTimelineShareData','scanQRCode']
        });
        wx.ready(function(){
          statusEl.innerHTML = '<span class="ok">wx.ready 成功，JSSDK 可用</span>'; 
          // setupShare();
        });
        wx.error(function(err){
          errorEl.textContent = 'wx.error: ' + JSON.stringify(err);
          statusEl.textContent = 'JSSDK 初始化失败';
        });
      } catch (e) {
        errorEl.textContent = e.message;
        statusEl.textContent = '签名获取失败';
      }
    }

    document.getElementById('btnCheck').addEventListener('click', function(){
      wx.checkJsApi({
        jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData'],
        success: function(res) { appendLog('checkJsApi: ' + JSON.stringify(res)); },
        fail: function(err) { appendLog('checkJsApi fail: ' + JSON.stringify(err)); }
      });
    });

    document.getElementById('btnResetShare').addEventListener('click', setupShare);

    document.getElementById('btnScanQRCode').addEventListener('click', function(){
      wx.scanQRCode({
        needResult: 1,
        scanType: ['qrCode','barCode'],
        success: function(res) { appendLog('scanQRCode: ' + JSON.stringify(res)); },
        fail: function(err) { appendLog('scanQRCode fail: ' + JSON.stringify(err)); }
      });
    });

    init();
  </script>
</body>
</html>